"""
helper function for telegram-bot-shadowrun
license: AGPL-3.0-only, see COPYING
"""
import random
from src.config import HITS, FAILS, DICE, DEFAULT_AMOUNT, LIMIT_DICE

def get_roll(amount: int, inject_numbers:list = None) -> dict:
    """gets a roll for amount dice, amount > 0
    inject_numbers can be used to inject numbers instead of random.randint
    return: dictionary with result, hits, fails, isFailure"""

    roll = {}
    roll["result"] = []
    roll["hits"] = 0
    roll["fails"] = 0
    roll["isFailure"] = False

    count = amount
    while count > 0:
        # if injected, use instead
        if inject_numbers and len(inject_numbers) > (amount-count):
            num = inject_numbers[amount-count]
        else:
            num = random.choice(DICE)

        roll["result"].append(num)
        if num in HITS:
            roll["hits"] += 1
        elif num in FAILS:
            roll["fails"] += 1
        count -= 1

    roll["isFailure"] = roll["fails"] > int(amount/2)
    return roll


def create_roll_reply(amount: list) -> str:
    """creates a string which rolls dice for /roll x
    x dice, if x not given, roll DEFAULT_AMOUNT
    amount: a list, which first element should be a int/a string of an int
    returns pseudo-random numbers provided by python's random, meaning seed is system time
    NOTE: if cheating is something to worry about, a better source of randomness should be used"""

    # set amount
    if not amount:
        amount = DEFAULT_AMOUNT
    else:
        amount = amount[0]
        try:
            amount = int(amount)
            if amount > LIMIT_DICE or amount < 1:
                amount = None
        except ValueError:
            amount = None

    # create response
    if amount:
        roll = get_roll(amount)
        reply = f"Result: {roll['result']}\n"
        if not roll["isFailure"]:
            reply += f"Hits: {roll['hits']}"
        else:
            reply += "Failure!"
    else:
        reply = "Enter a valid integer between 0 and 100"
    return reply
